import React, {
  useState, useEffect, useMemo, useRef, useCallback,
} from 'react'
import {
  Text, View, SafeAreaView, Image, TextInput,
} from 'react-native'
import RNExitApp from 'react-native-exit-app'
import { RouterKey } from '@NAVIGATION/NavigationType'
import Api from '@API'
import EStyleSheet from 'react-native-extended-stylesheet'
import Navigation from '@NAVIGATION/Navigation'
import LinearGradient from 'react-native-linear-gradient'
import Button from '@COMPONENTS/button/Button'
import Images from '@IMAGE'
import { validation } from '@pier88health/p8h-common'
import Storage, { StorageKey } from '@UTILS/Storage'
import initConfig from '@UTILS/policy'
import { useAppDispatch, useAppSelector } from '@REDUX/store'
import { actions } from '@REDUX/reducer/user'
import Toast from '@COMPONENTS/Toast'
import AppUpdatePopup from '@COMPONENTS/Popup/AppUpdatePopup'
import AppPrivacyAgreement from '@COMPONENTS/Popup/AppPrivacyAgreement'
import useCountdown from '@HOOKS/useCountdown'
import AnalyticsUtil from '@UTILS/AnalyticsUtil'
import { openAppStore } from '@UTILS/Common'

const NUMBER_REG = /^[1][0-9]{0,10}$/
const CODE_REG = /^[0-9]{0,4}$/
const COLORS_ARR = ['#7CD795', '#6ED58B']
const DISABLED_COLORS = ['#FFF', '#FFF']

const getIsNewUsers = async () => {
  const isNewUsers = await Storage.get(StorageKey.isNewUsers)
  return isNewUsers === null
}

const appFirstLoad = async () => {
  const displayedPrivacyPolicy = Storage.get(StorageKey.displayedPrivacyPolicy)
  return displayedPrivacyPolicy
}

const Login: React.FC = () => {
  const user = useAppSelector((state: { user: any }) => state.user)
  const { UserName } = user.user || {}
  const appUpdatInfo = user.appUpdatInfo || {}
  const { ForceUpdate, ...updateInfo } = appUpdatInfo
  const dispatch = useAppDispatch()
  const [phone, setPhone] = useState('')
  const [code, setCode] = useState('')
  const [showPopup, setPopup] = useState([false, false])
  const [agree, setAgree] = useState(false)
  const [start, setStart] = useState(0)
  const { s: second } = useCountdown({
    totalSecond: 60,
    start: start > 0,
    onEnd: () => setStart(0),
  })
  const count = Number(second)
  const refData = useRef({ getOnce: false, ActionTokenId: '' })
  const codeDisabled = !phone
  const loginDisabled = !code

  const codeText = useMemo(() => {
    let text = '获取验证码'
    if (refData.current.getOnce) {
      text = '重发验证码'
    }
    if (count > 0) {
      text = `${count}秒后可重发`
    }
    return text
  }, [count])

  const onChangeText = (val:string) => {
    if (NUMBER_REG.test(val) || val === '') {
      setPhone(val)
    }
  }

  const onChangeCode = (val:string) => {
    if (CODE_REG.test(val) || val === '') {
      setCode(val)
    }
  }

  const login = async () => {
    if (agree) {
      const userData = await Api.loginByPhone({
        PhoneNumber: phone,
        ActionTokenId: refData.current.ActionTokenId,
        AuthCode: code,
      })
        .catch((e) => {
          Toast.error(e, { source: Images.login.warn })
          return null
        })
      if (!userData) return
      AnalyticsUtil.profileSignInWithPUID?.(userData.UserName)
      Storage.set(StorageKey.token, userData.UserToken)
      Storage.set(StorageKey.userId, userData.p8Id)
      dispatch(actions.loginSuccess(userData))
      const isNewUsers = await getIsNewUsers()

      if (isNewUsers) {
        Navigation.replace(RouterKey.BluetoothGuide, { fromPage: RouterKey.BluetoothGuide })
        Storage.set(StorageKey.isNewUsers, false)
      } else {
        Navigation.replace(RouterKey.Root)
      }
    } else {
      Toast.info('请先阅读并同意《纳瑞维用户协议》及\n《隐私政策》')
    }
  }

  const onClear = () => setPhone('')

  const onGetCode = () => {
    if (count) return
    if (validation.isPhoneNumber(phone)) {
      refData.current.getOnce = true
      setStart(60)
      Api.requestAuthCode({ PhoneNumber: phone })
        .then((res) => {
          refData.current.ActionTokenId = res.ActionTokenId
        }).catch((e) => {
          Toast.error(e.message || e)
        })
    } else {
      Toast.error('手机格式不正确')
    }
  }
  const clearCode = () => setCode('')
  const onAgree = () => setAgree(!agree)
  // todo h5跳转
  const userAgreement = () => {}
  const privacyAgreement = () => {}

  const confirmPrivacy = useCallback(() => {
    setPopup([false, showPopup[1]])
    Storage.set(StorageKey.displayedPrivacyPolicy, true)
    initConfig()
  }, [showPopup])

  const cancelPrivacy = () => {
    RNExitApp.exitApp()
  }

  const confirmUpdate = useCallback(() => {
    setPopup([showPopup[0], false])
    openAppStore()
  }, [showPopup])

  const setPopupFun = useCallback(async () => {
    const isFirstLoad = await appFirstLoad()
    setPopup([isFirstLoad === null, ForceUpdate])
  }, [ForceUpdate])

  useEffect(() => {
    setPhone(UserName)
  }, [UserName])

  useEffect(() => {
    setPopupFun()
  }, [ForceUpdate, setPopupFun])

  return (
    <SafeAreaView style={styles.safeAreaView}>
      <Image source={Images.login.logo} style={styles.logo} />
      <Text style={styles.text}>纳瑞维</Text>
      <View style={styles.container}>
        <View style={styles.phoneBox}>
          <TextInput
            keyboardType="phone-pad"
            style={[styles.phone]}
            placeholder="请输入手机号码"
            placeholderTextColor="#8C8C8C"
            onChangeText={onChangeText}
            value={phone}
          />
          {phone && (
          <Button onPress={onClear}>
            <Image source={Images.login.clear} style={styles.clear} />
          </Button>
          )}
        </View>

        <View style={styles.phoneBox}>
          <TextInput
            keyboardType="numeric"
            style={[styles.phone]}
            placeholder="填写短信验证码"
            placeholderTextColor="#8C8C8C"
            onChangeText={onChangeCode}
            value={code}
          />
          <View style={styles.codeBox}>
            {code && (
            <Button onPress={clearCode}>
              <Image source={Images.login.clear} style={styles.clear} />
            </Button>
            )}
            <Button onPress={onGetCode}>
              <View style={styles.getCodeBox}>
                <Text style={[styles.getCode, [codeDisabled, count > 0].includes(true) && styles.noCode]}>
                  {codeText}
                </Text>
              </View>
            </Button>
          </View>
        </View>

        <LinearGradient
          colors={!loginDisabled ? COLORS_ARR : DISABLED_COLORS}
          style={[styles.button, loginDisabled && styles.disabledButton]}
        >
          <Button style={{}} onPress={login}>
            <Text style={[styles.buttonText, loginDisabled && styles.disabled]}>登陆</Text>
          </Button>
        </LinearGradient>

        <Text style={styles.tipText}>未注册手机号验证后将自动登录</Text>
      </View>

      <View style={styles.agreement}>
        <Button onPress={onAgree}>
          <Image
            style={styles.check}
            source={agree ? Images.login.checked : Images.login.noCheck}
          />
        </Button>
        <Text style={styles.agreementText}>我已阅读并同意</Text>
        <Text style={[styles.agreementText, styles.link]} onPress={userAgreement}>《纳瑞维用户协议》</Text>
        <Text style={styles.agreementText}>及</Text>
        <Text style={[styles.agreementText, styles.link]} onPress={privacyAgreement}>《隐私政策》</Text>
      </View>
      {showPopup[0] && <AppPrivacyAgreement onCancel={cancelPrivacy} onConfirm={confirmPrivacy} />}
      {/* @ts-ignore */}
      {!!updateInfo && showPopup[1] && !showPopup[0] && <AppUpdatePopup updateInfo={appUpdatInfo} onConfirm={confirmUpdate} />}
    </SafeAreaView>

  )
}

export default Login

const styles = EStyleSheet.create({
  safeAreaView: {
    flex: 1,
    backgroundColor: '$white',
  },
  logo: {
    marginTop: 52,
    marginBottom: 12,
    alignSelf: 'center',
  },
  text: {
    fontSize: 24,
    fontFamily: 'PingFangSC-Medium',
    fontWeight: '500',
    color: '$fontColor',
    lineHeight: 33,
    textAlign: 'center',
    marginBottom: 60,
  },
  container: {
    paddingLeft: 32,
    paddingRight: 32,
    flex: 1,
  },
  phoneBox: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'flex-start',
    marginBottom: 36,
    borderBottomColor: '$border',
    borderBottomWidth: 0.5,
  },
  phone: {
    paddingBottom: 15,
    fontSize: 16,
    fontFamily: 'PingFangSC-Regular',
    fontWeight: '400',
    color: '$fontColor',
    lineHeight: 22,
    flex: 1,
  },
  clear: {
    width: 17,
    height: 17,
  },
  codeBox: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  getCodeBox: {
    borderLeftColor: '$border',
    borderLeftWidth: 0.5,
    height: 20,
    marginLeft: 16,
    width: 130,
  },
  getCode: {
    fontSize: 16,
    fontFamily: 'PingFangSC-Regular',
    fontWeight: '400',
    color: '$theme',
    lineHeight: 22,
    textAlign: 'right',
  },
  noCode: {
    color: '$disabled',
  },
  button: {
    height: 54,
    borderRadius: 8,
    borderWidth: 1,
    borderColor: 'transparent',
  },
  disabledButton: {
    backgroundColor: '#FFF',
    borderColor: '$disabled',
  },
  buttonText: {
    fontSize: 16,
    fontFamily: 'PingFangSC-Regular',
    fontWeight: '400',
    color: '#FFF',
    lineHeight: 54,
    height: 54,
    textAlign: 'center',
  },
  disabled: {
    color: '$disabled',
  },
  tipText: {
    fontSize: 12,
    fontFamily: 'PingFangSC-Light',
    fontWeight: '300',
    color: '#8C8C8C',
    lineHeight: 17,
    marginTop: 12,
    textAlign: 'center',
  },
  agreement: {
    marginBottom: 48,
    paddingLeft: 34,
    flexDirection: 'row',
    alignItems: 'center',
  },
  agreementText: {
    fontSize: 12,
    fontFamily: 'PingFangSC-Light',
    fontWeight: '300',
    color: '$fontColor',
    lineHeight: 17,
  },
  link: {
    fontFamily: 'PingFangSC-Regular',
    color: '$theme',
    fontWeight: 'bold',
    paddingLeft: 5,
    paddingRight: 5,
  },
  check: {
    marginRight: 10,
  },
})
